package com.xbb.controller.excel;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import com.xbb.entity.Teacher;
import com.xbb.entity.dto.TeacherDto;
import com.xbb.service.TeacherService;
import com.xbb.util.PoiUtils;
import com.xbb.util.Result;
@RestController
@RequestMapping("teaexcel")
public class TeacherExcelController {
	
		@Autowired
		TeacherService service;
		
		@RequestMapping("/exportTea")
		public void exportTea(HttpServletResponse response, String ids)
				throws IOException {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");
			String time = sdf.format(new Date());
			String downloadName = "导出的文件"+time+".xls";
			response.setCharacterEncoding("UTF-8");// 设置响应的字符编码格式
			response.setContentType("application/vnd.ms-excel");// 指明响应文件为excel类型
			response.setHeader("Content-disposition", "attachment;filename="
					+ new String(downloadName.getBytes("GB2312"), "ISO8859-1"));// 文件名编码处理，防止浏览器下载文件名乱码
			ServletOutputStream out = response.getOutputStream();
			List<TeacherDto> list = new ArrayList<TeacherDto>();
			System.out.println("ids" + ids);
			if (ids != null && !ids.equals("")) {
				list = service.queryByIds(ids);
				System.out.println("选中的数据集合=>" + list);
			} else {
				//全查
				list = service.getTeas(null);
				System.out.println(list);
			}
			try {
				PoiUtils p = new PoiUtils();
				p.createExcel(list, Teacher.class, out);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		
		@RequestMapping(value = "/uploadTea", name = "导入教师")
		public Object uploadTea(@RequestParam(value = "file") MultipartFile file) {
			String name = file.getName();// form表单中参数名称
			String originalFilename = file.getOriginalFilename();// 得到上传文件的名称
			System.out.println("表单中文件参数名称 name=>" + name);
			System.out.println("上传的文件原始名称 originalfileName=>" + originalFilename);
			PoiUtils poiUtils = new PoiUtils();// Excel工具类
			List<Teacher> list = null;
			int n = 1;
			try {
				list = (List<Teacher>) poiUtils.parseExcel(Teacher.class, file.getInputStream(), originalFilename);
				System.out.println("导入的数据长度：" + list.size());
				for (Teacher  e: list) {
					 service.addTea(e);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
			if (list!=null) {
				return new Result(0, "上传成功", true);
			} else {
				return new Result(1, "上传失败", false);
			}
		}

	}
